package com.zcs.thread.communication;

/**
 * 通信--锁与通步
 * 两个线程保持顺序执行
 * @author zcs
 * @since 2023/4/21
 */
public class ObjectLock {

    private static final byte[] LOCK = new byte[0];

    /**
     * 基于“锁”的方式，线程需要不断地去尝试获得锁，如果失败了，再继续尝试。这可能会耗费服务器资源。
     * @param args
     * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        new ThreadA().aVoid();
        Thread.sleep(10);
        new ThreadB().bVoid();
    }


    static class ThreadA {

        public void aVoid() {
            new Thread(() -> {
                synchronized (LOCK) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println("Thread A " + i);
                    }
                }
            }).start();
        }
    }

    static class ThreadB {
        public void bVoid() {
            new Thread(() -> {
                synchronized (LOCK) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println("Thread B " + i);
                    }
                }
            }).start();
        }
    }

}
